package main

import (
	"fmt"
	"math/rand"
	"time"
)

/**
	select 调度
	1.select使用
	2. 定时器的使用
	3. nil channel 的使用
 */

func generator() chan int{
	out := make(chan int)
	go func() {
		i := 0
		for {
			time.Sleep(time.Duration(rand.Intn(1500)) * time.Millisecond)
			out <- i
			i++
		}
	}()
	return out
}
func worker(id int, c chan int)  {
	for n := range c { //判断channel为空
		time.Sleep(time.Second)
		fmt.Printf("worker %d received %d \n", id, n)
	}
}

func createWorker(id int) chan<- int {
	c := make(chan int)
	go worker(id, c)
	return c
}

func main() {
	var c1, c2 = generator(), generator()
	//w := createWorker(0)
	var worker = createWorker(0)
	n := 0
	//hasValue := false
	var values []int
	tm := time.After(10 * time.Second) //
	tick := time.Tick(time.Second) //定时
	for {
		var activeWorker chan <- int
		var activeValue int
		if len(values) > 0 {
			activeWorker = worker
			activeValue = values[0]
		}
		select {
		case n = <- c1:
			//fmt.Println("chan c1 is done", n)
			//hasValue = true
			values = append(values, n)
		case n = <- c2:
			//fmt.Println("chan c2 is done", n)
			//hasValue = true
			values = append(values, n)
		case activeWorker <- activeValue:
			//hasValue = false
			values = values[1:]
		case <-tm:  //运行时间，过期之后会退出
			fmt.Println("bye")
			return
		case <- time.After(800 * time.Millisecond):  //select 运行超时会报错
			fmt.Println("time out")
			return
		case <- tick:
			fmt.Println("queue len", len(values))
		//default:
		//	fmt.Println("no chan")
		}
	}


}